<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\UserPermission;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class BackendUsersController extends Controller
{
    /**
     * 构造函数，添加中间件验证
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('admin'); // 假设你有一个 admin 中间件来验证管理员权限
    }

    /**
     * 显示用户列表
     */
    public function index()
    {
        $users = User::with('permission')->latest()->paginate(10);
        $permissions = UserPermission::all();
        return view('BackendUsers.index', compact('users', 'permissions'));
    }

    /**
     * 显示创建用户表单
     */
    public function create()
    {
        return view('BackendUsers.create');
    }

    /**
     * 保存新用户
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

        User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
        ]);

        return redirect()->route('users.index')
            ->with('success', '用户创建成功！');
    }

    /**
     * 显示编辑用户表单
     */
    public function edit(User $user)
    {
        return view('BackendUsers.edit', compact('user'));
    }

    /**
     * 更新用户信息
     */
    public function update(Request $request, User $user)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users,email,' . $user->id,
            'password' => 'nullable|string|min:8|confirmed',
        ]);

        $userData = [
            'name' => $validated['name'],
            'email' => $validated['email'],
        ];

        if (!empty($validated['password'])) {
            $userData['password'] = Hash::make($validated['password']);
        }

        $user->update($userData);

        return redirect()->route('users.index')
            ->with('success', '用户信息更新成功！');
    }

    /**
     * 删除用户
     */
    public function destroy(User $user)
    {
        // 防止删除自己
        if ($user->id === auth()->id()) {
            return back()->with('error', '不能删除当前登录用户！');
        }

        $user->delete();

        return redirect()->route('users.index')
            ->with('success', '用户删除成功！');
    }

    /**
     * 更新用户权限
     */
    public function updatePermission(Request $request, User $user)
    {
        try {
            \Log::info('权限更新请求', [
                'user_id' => $user->id,
                'attribute_id' => $request->attribute_id,
                'auth_user' => auth()->user()
            ]);

            $validated = $request->validate([
                'attribute_id' => 'required|exists:user_permissions,id'
            ]);

            $user->update([
                'attribute_id' => $validated['attribute_id']
            ]);

            \Log::info('用户权限更新成功', [
                'user_id' => $user->id,
                'attribute_id' => $validated['attribute_id']
            ]);

            return response()->json([
                'success' => true,
                'message' => '权限更新成功'
            ]);
        } catch (\Exception $e) {
            \Log::error('用户权限更新失败', [
                'error' => $e->getMessage(),
                'user_id' => $user->id,
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'success' => false,
                'message' => '权限更新失败：' . $e->getMessage()
            ], 500);
        }
    }
} 